<template>
	<div class="login">
		<el-form class="login-form">
			<h3 class="title">失物招领系统</h3>
			<el-form-item prop="username">
				<el-input 
				v-model="username" 
				placeholder="请输入账号" 
				class="login-input"
				></el-input>
			</el-form-item prop="password">
			
			<el-form-item prop="username">
				<el-input 
				v-model="password" 
				placeholder="请输入密码"
				show-password
				></el-input>
			</el-form-item prop="password">  
			  <el-form-item>
					<el-button type="primary" @click="onSubmit">登录</el-button>
					<el-button type="primary" @click="onRegister">注册</el-button>
			  </el-form-item>
		</el-form>
	</div>
</template>
	
<script>
	import axios from 'axios'
	import {mapMutations} from 'vuex'
export default {
  data() {
    return {
      username: '',
	  password: ''
    }
  },
  methods:{ 
	  ...mapMutations('User',['USER_INIT']),
	  onSubmit() {
		  console.log("login start!")
		  if(this.username && this.password) {
			  axios.get('http://localhost:3000/login',{
			  params: {
				  username:this.username,
				  password:this.password
			  }
			})
			.then(value=> {
				if(value.data) {
					
					//注册当前用户到store
					this.USER_INIT(value.data);
					
					//如果用户是第一次登录，就需要注册localStorage
					if(!localStorage.getItem('_id') || value.data._id != localStorage.getItem('_id')) {
						localStorage.setItem('_id', value.data._id)
						localStorage.setItem('username', value.data.username)
						localStorage.setItem('password', value.data.password)
						localStorage.setItem('sex', value.data.sex)
						localStorage.setItem('avatar', value.data.avatar)	
					}
					
					this.$router.push('/layout')
				}else {
					this.$message.error("用户名或密码错误")
				}
				
				
				
				
			})
		  } else {
			  this.$message.info('请输入账号或者密码')
		  }
		  
			console.log("login end!")
	  },
	  onRegister() {
		  this.$router.push('/register')
	  }
  }
  
}
</script>

<style>
	.login {
		position: fixed;
		height: 100%;
		width: 100%;
		background-color: #f5f5f5;
		
	}
	.login-form {
		position: absolute;
		left: 0;
		right: 0;
		width: 300px;
		padding: 25px 35px 15px 35px;
		margin: 25vh auto;
		background-color: #e3e3e3;
		box-shadow: 0 0 8px gray;
		border-radius: 5px;
	}
	.title {
		height: 55px;
		font-size: 25px;
	}
	.login-input {
		outline: none;
		height: 50px;
	}
	el-input {
		outline: none;
		height: 50px;
	}
</style>
